package com.ld.oauth2.config.oauth;

import com.ld.oauth2.config.filter.MyUsernamePasswordAuthenticationFilter;
import com.ld.oauth2.config.oauth.handle.CustomAuhtenticationFailureHandler;
import com.ld.oauth2.config.oauth.handle.CustomAuhtenticationSuccessHandler;
import com.ld.oauth2.config.oauth.handle.CustomInvalidSessionHandle;
import com.ld.oauth2.config.oauth.handle.CustomLogoutHandler;
import com.ld.oauth2.config.properties.SecurityProperties;
import com.ld.oauth2.service.CustomUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import java.net.InetAddress;

/**
 * 安全配置类  也就是用户向认证服务器进行认证的类
 * 这里会校验用户的用户名和密码
 */
@EnableWebSecurity
@Order(2)
@Slf4j
public class AuthSpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private CustomUserDetailsService customUserDetailService;

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private CustomAuhtenticationSuccessHandler customAuhtenticationSuccessHandler;

    @Autowired
    private CustomAuhtenticationFailureHandler customAuhtenticationFailureHandler;

    @Autowired
    private SessionInformationExpiredStrategy sessionInformationExpiredStrategy;

//    @Autowired
//    private MyUsernamePasswordAuthenticationFilter myAuthenticationFilter;


    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailService);

    }

    @Bean//passwod模式需要这个bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        //web.ignoring().antMatchers(securityProperties.getStaticPaths());
//        web.ignoring().anyRequest();
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        log.info("hostAddress={}",hostAddress);
        http
//                .addFilterAt(myAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .formLogin()
                .loginPage("http://"+hostAddress+":7000")
                .loginProcessingUrl(securityProperties.getLoginProcessingUrl())
                .usernameParameter(securityProperties.getUsernameParameter())
                .passwordParameter(securityProperties.getPasswordParameter())
                .successHandler(customAuhtenticationSuccessHandler)
                .failureHandler(customAuhtenticationFailureHandler)
                .and()
//                .sessionManagement()
//                .invalidSessionStrategy(invalidSessionStrategy())
//                .maximumSessions(1)
//                .expiredSessionStrategy(sessionInformationExpiredStrategy)
//                .sessionRegistry(sessionRegistry())
//                .and().and()
//
                .authorizeRequests()
                .antMatchers("/auth/ld/login","/auth/oauth/**").permitAll()
//                .and()
//                .logout()
//                .addLogoutHandler(customLogoutHandler()) // 退出清除缓存
//                .logoutUrl("/user/logout") // 退出请求路径
//                .logoutSuccessUrl("http://localhost:7000/?redirectURL=http://localhost:9001/client1") //退出成功后跳转地址
//                .deleteCookies("JSESSIONID") // 退出后删除什么cookie值
        ;
        http.csrf().disable();

    }



    @Bean
    public CustomLogoutHandler customLogoutHandler() {
        CustomLogoutHandler customLogoutHandler = new CustomLogoutHandler();
        customLogoutHandler.setSessionRegistry(sessionRegistry());
        return customLogoutHandler;
    }

    /**
     * 当session失效后的默认处理类
     *
     * @return
     */
    @Bean
    public InvalidSessionStrategy invalidSessionStrategy() {
        CustomInvalidSessionHandle invalidSessionStrategy = new CustomInvalidSessionHandle();
        invalidSessionStrategy.setSessionRegistry(sessionRegistry());
        return invalidSessionStrategy;
    }

    @Bean
    MyUsernamePasswordAuthenticationFilter myAuthenticationFilter() throws Exception {
        MyUsernamePasswordAuthenticationFilter filter = new MyUsernamePasswordAuthenticationFilter(securityProperties.getLoginProcessingUrl());
        filter.setAuthenticationManager(authenticationManager());
        filter.setAuthenticationSuccessHandler(customAuhtenticationSuccessHandler);
        filter.setAuthenticationFailureHandler(customAuhtenticationFailureHandler);
        filter.setUsernameParameter(securityProperties.getUsernameParameter());
        filter.setPasswordParameter(securityProperties.getPasswordParameter());
         return filter;
    }

}
